/**
 * Copyright (C) 2018-2019
 * All rights reserved, Designed By www.joolun.com
 */
package com.ruoyi.mall.dubbo;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.mall.api.RemoteGoodsCategoryService;
import com.ruoyi.mall.api.constant.CommonConstants;
import com.ruoyi.mall.api.entity.GoodsCategory;
import com.ruoyi.mall.api.entity.GoodsCategoryTree;
import com.ruoyi.mall.mapper.GoodsCategoryMapper;
import com.ruoyi.mall.utils.TreeUtil;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品类目
 *
 * @author www.joolun.com
 * @date 2019-08-12 11:46:28
 */
@Service
@DubboService
public class RemoteGoodsCategoryServiceImpl extends ServiceImpl<GoodsCategoryMapper, GoodsCategory> implements RemoteGoodsCategoryService {

    @Override
    public List<GoodsCategoryTree> selectTree(GoodsCategory goodsCategory) {
        return getTree(this.list(Wrappers.lambdaQuery(goodsCategory)));
    }

    /**
     * 构建树
     *
     * @param entitys
     * @return
     */
    private List<GoodsCategoryTree> getTree(List<GoodsCategory> entitys) {
        List<GoodsCategoryTree> treeList = entitys.stream()
            .filter(entity -> !entity.getId().equals(entity.getParentId()))
            .sorted(Comparator.comparingInt(GoodsCategory::getSort))
            .map(entity -> {
                GoodsCategoryTree node = new GoodsCategoryTree();
                BeanUtil.copyProperties(entity, node);
                return node;
            }).collect(Collectors.toList());
        return TreeUtil.build(treeList, CommonConstants.PARENT_ID);
    }

    @Override
    public boolean removeById(Serializable id) {
        super.removeById(id);
        remove(Wrappers.<GoodsCategory>query()
            .lambda().eq(GoodsCategory::getParentId, id));
        return true;
    }

    @Override
    public IPage page(Page page, GoodsCategory goodsCategory) {
        return super.page(page, Wrappers.query(goodsCategory));
    }

    @Override
    public GoodsCategory getById(String id) {
        return super.getById(id);
    }

    @Override
    public boolean save(GoodsCategory entity) {
        return super.save(entity);
    }

    @Override
    public boolean updateById(GoodsCategory entity) {
        return super.updateById(entity);
    }

    @Override
    public boolean removeById(String id) {
        return super.removeById(id);
    }
}
